package com.jinjie.baselibrary;

import android.app.Activity;
import android.icu.text.DateFormat;
import android.view.View;

import java.lang.reflect.Field;

/**
 * Created by syd_123 on 2018/3/15.
 * http://blog.csdn.net/dong19900415
 */

public class ViewUtils {


    public static void inject(Activity activity) {
        inject(new ViewFinder(activity), activity);

    }

    public static void inject(View view) {
        inject(new ViewFinder(view), view);
    }

    public static void inject(View view, Object object) {

        inject(new ViewFinder(view), object);

    }

    //兼容上边的三个方法
    private static void inject(ViewFinder finder, Object object) {
        injectFiled(finder, object);
        injectEvent(finder, object);
    }

    //注入属性
    private static void injectFiled(ViewFinder finder, Object object) {
        //1、注入所有的属性
        Class<?> clazz = object.getClass();
        //获取所有的属性
        Field[] fields = clazz.getDeclaredFields();

        //2、获取ViewById的所有值

        for (Field field : fields) {
            ViewById viewById = field.getAnnotation(ViewById.class);
            if (viewById != null) {
                int viewId = viewById.value();
                //3、findViewById找到View
                View view = finder.findViewById(viewId);
                if (view != null) {
                    field.setAccessible(true);
                    try {
                        field.set(object, view);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }

            }
        }

        //4、动态注入找到的view

    }

    private static void injectEvent(ViewFinder finder, Object object) {
    }
}

